import 'dotenv/config'

import http from 'http';
import fs from 'fs/promises';
import url from 'url';
import path from 'path';
import { Console } from 'console';

const _filename = url.fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);

console.log(_dirname,_filename);

const PORT = process.env.PORT;

const server = http.createServer(async (req,res) => {
    try{
        if(req.method === 'GET'){
            let filePath;
            if(req.url === '/'){
                filePath = path.join(_dirname,'public','index.html');
            //     res.writeHead(200,{'Content-Type':'text/html'});
            //    res.end('<h1>主页</h1>');
                } else if(req.url === '/about'){
                    filePath = path.join(_dirname,'public','about.html');
                    // res.writeHead(200,{'Content-Type':'text/html'});
                    // res.end('<h1>关于</h1>');
            }else{
                res.writeHead(404,{'Content-Type':'text/html;charset=utf-8'});
                //throw new Error('页面未找到')
                res.end('<h1>页面未找到</h1>');
                // res.writeHead(404,{'Content-Type':'text/html'});
                //     res.end('<h1>404 无法找到此页</h1>');
            }
            const data = await fs.readFile(filePath);
            res.setHeader('Content-Type','text/html;charset=utf-8');
            res.writeHead(200);
            res.end(data);
        }else{
            throw new Error('<h1>非法请求</h1>');
        }
    }catch(error){
        console.log(error);
        res.writeHead(500,{'Content-Type':'text/html;charset=utf-8'});
        res.end('<h1>服务器错误</h1>');
    }
   // res.write('Hello World!');
//    res.setHeader('Content-Type','text/html')
//     res.statusCode = 404;
//     res.end('<h1>Hello World!</h1>');
// res.writeHead(500, {'Content-Type': 'application/json'});
// res.end(JSON.stringify({message: "服务器错误"}));
});

server.listen(8000, () => {
    console.log("服务器已启动，监听端口8000${PORT}");
});